<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Modules\User\Models\Feedback;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;

class FeedbackController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('feedback');
        $readNoread = $request->input('read_no_read');

        $data = Feedback::query()
            ->join('users', 'users.id', '=', 'feedback.user_id')
            ->when(!is_null($readNoread), function ($query) use ($readNoread) {
                return $query->where('feedback.read_noread', $readNoread);
            })
            ->select('feedback.*', 'users.nickname', 'users.avatar')
            ->orderBy('feedback.created_at', 'desc')
            ->paginate(20);
        if (!empty($data->image)) {
            $image = '';
            foreach ($data->image as $value) {
                $image = $value.";";
            }
            $data->image = $image;
        }

        return view('feedback.index', compact('readNoread','data'));
    }

    /**
     * 已读操作
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function read($id){
        $this->authorize('feedback-read');
        Feedback::query()
            ->where('id', $id)
            ->update([
                'read_noread' => 1,
            ]);
        return redirect()->back();
    }
}
